import ctypes

lib = ctypes.cdll.LoadLibrary(r'B:\codes\C_Cpp\DMuse\ReaperRemoteMMAP_2.dll')

send_tagname = b'rpr_c2r_1'
recv_tagname = b'rpr_r2c_1'
n_chan = 10

empty = b'\x00' * 1024

lib.Listen(ctypes.c_char_p(send_tagname), ctypes.c_char_p(recv_tagname), 1024, n_chan)

last_obj = ''

def send(ch, obj):
    b2 = str(obj).encode('utf-8')
    # RPR_ShowConsoleMsg('send: ' + str(ch) + ' ' + str(obj) + ' ' + str(b2) + '\n')
    lib.PushMsg(ch, b2, len(b2))

def recv(ch):
    s = empty
    p = ctypes.c_char_p(s)
    lib.GetMsg(ch, p)
    # RPR_ShowConsoleMsg('recv: ' + str(ch) + ' ' + str(p.value)  + '\n')
    if not p.value:
        return None
    try:
        return str(p.value, encoding='utf-8')
    except Exception:
        return None

def loop():
    global last_obj
    for ch in range(n_chan):
        obj = recv(ch)
        
        if obj is not None and obj != last_obj:
            evl = None
            while True:
                try:
                    evl = eval(obj)
                except NameError:
                    obj = recv(ch)
                    continue
                except SyntaxError:
                    obj = recv(ch)
                    continue
                break
            RPR_ShowConsoleMsg(str(ch) + '  ' + str(obj) + str(evl) + '\n')
            last_obj = obj
            lib.ClearSend(ch)
            send(ch, evl)
        
    # RPR_ShowConsoleMsg(msg_id + ' ' + msg)
    RPR_defer('loop()')


loop()


